package com.lagou.filter;

import com.alibaba.fastjson.JSON;
import com.lagou.config.IpParam;
import com.lagou.config.SpringUtil;
import com.lagou.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

//@RefreshScope
@Component
public class IpFilter implements GatewayFilter, Ordered {

    private Map<String, List<Date>> ipMap = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        IpParam bean = SpringUtil.getBean(IpParam.class);
        int time = bean.getTime();
        String url = bean.getUrl();
        int number = bean.getNumber();
        ServerHttpRequest request = exchange.getRequest();
        if (request.getPath().toString().startsWith(url)){
            ServerHttpResponse response = exchange.getResponse();
            String host = request.getRemoteAddress().getHostString();
            Date currentDate = new Date();
            List<Date> list = null;
            synchronized (this){
               list = ipMap.get(host);
            }
            if (list != null && list.size() >= number){
                Date date = list.get(list.size() - number);
                if (currentDate.getTime() - date.getTime() < time * 60 * 1000){
                    //此ip拒绝访问
                    ResponseData responseData = ResponseData.fail("系统繁忙，请稍后再试");
                    String json = JSON.toJSONString(responseData);
                    byte[] bits = json.getBytes(StandardCharsets.UTF_8);
                    DataBuffer buffer = response.bufferFactory().wrap(bits);
                    response.setStatusCode(HttpStatus.OK);
                    //指定编码，否则在浏览器中会中文乱码
                    response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                    return response.writeWith(Mono.just(buffer));
                }
            }
            if (list == null){
                list = new ArrayList<>();
                ipMap.put(host,list);
            }
            list.add(currentDate);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
